package com._13read.rss.manager.impl;

import cn.hutool.http.HttpUtil;
import com._13read.rss.config.WxMpConfig;
import com._13read.rss.manager.IWxMpUserManager;
import com._13read.rss.model.WxMpJscode2SessionResult;
import com._13read.rss.model.WxMpUserInfo;
import com._13read.rss.util.AESUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WxMpUserManagerImpl implements IWxMpUserManager  {

    @Autowired
    private WxMpConfig wxMpConfig;

    public void login(String code) {
        WxMpJscode2SessionResult wxMpJscode2SessionResult = code2Session(code);
        log.info(JSONObject.toJSONString(wxMpJscode2SessionResult));
        
    }

    public WxMpJscode2SessionResult code2Session (String code){
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid",wxMpConfig.getAppid());
        paramMap.put("secret",wxMpConfig.getSecret());
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");
        String result = HttpUtil.get(wxMpConfig.getJscode2session(), paramMap);
        WxMpJscode2SessionResult wxMpJscode2SessionResult = WxMpJscode2SessionResult.fromJson(result);
        return wxMpJscode2SessionResult;
    }

    public WxMpUserInfo getUserInfo (String sessionKey, String encryptedData, String ivStr){
        String decrypt = AESUtil.decrypt(sessionKey, encryptedData, ivStr);
        WxMpUserInfo wxMpUserInfo = WxMpUserInfo.fromJson(decrypt);
        // todo 开发者资质认证 open.weixin.qq.com
        wxMpUserInfo.setUnionId("");
        return wxMpUserInfo;

    }


}
